'use strict';
define(['../main','fileSaver'],function(module){

    module.controller("statisticCtrl",function($scope,$http,$rootScope){

        $rootScope.navActive='/web/statistic';
        $scope.searchInfo={};           //查询条件对象
        $scope.conditions=[             //查询条件元数据
            {title:"大区",key:"groups"},
            {title:"城市",key:"city"},
            {title:"支付类型",key:"payType"},
            {title:"订单类型",key:"orderType"},
            {title:"订单状态",key:"orderStatus"},
            {title:"运动类型",key:"sportsType"}
        ];
        $scope.currentTimeType={key:"",value:"日期类型"};      //当前日期类型
        $scope.selector={};             //查询下拉框数据汇总
        $scope.results=[];              //统计结果集
        $scope.startTime=addDate(-1);   //开始时间
        $scope.endTime=addDate(-1);     //结束时间
        $scope.searchKey="";            //搜索字符串
        $scope.resultsStr="";           //用于导出的数据字符串
        $scope.titles=[];               //标题
        $scope.shopDimensionIndex=-1;   //场馆维度序号
        $scope.orderDetail={};//{"pageNum":1,"pageSize":20,"size":20,"orderBy":null,"startRow":1,"endRow":20,"total":35,"pages":2,"list":[{"orderId":2761330,"shopId":2086,"shopCode":"54037","shopName":"黄石体育馆-羽毛球馆","sales":"张文","cityId":14,"cityName":"黄石","sportsType":4,"sportsTypeName":"羽毛球","orderNumber":1,"paySum":0,"fee":0,"subsidySum":0,"subsidyFee":0,"payType":null,"status":3,"statusName":"已使用","settleStatus":1,"settleStatusName":"未结算","orderTime":"2016-06-13 08:04:43.0","examineTime":"2016-06-14 16:00:00.0","useTime":"2016-06-14 13:53:02.0"},{"orderId":2761679,"shopId":2086,"shopCode":"54037","shopName":"黄石体育馆-羽毛球馆","sales":"张文","cityId":14,"cityName":"黄石","sportsType":4,"sportsTypeName":"羽毛球","orderNumber":1,"paySum":0,"fee":0,"subsidySum":0,"subsidyFee":0,"payType":null,"status":4,"statusName":"已过期(未使用)","settleStatus":1,"settleStatusName":"未结算","orderTime":"2016-06-13 09:48:18.0","examineTime":"2016-06-14 11:00:00.0","useTime":null},{"orderId":2766038,"shopId":2086,"shopCode":"54037","shopName":"黄石体育馆-羽毛球馆","sales":"张文","cityId":14,"cityName":"黄石","sportsType":4,"sportsTypeName":"羽毛球","orderNumber":1,"paySum":0,"fee":0,"subsidySum":0,"subsidyFee":0,"payType":null,"status":3,"statusName":"已使用","settleStatus":1,"settleStatusName":"未结算","orderTime":"2016-06-14 08:57:40.0","examineTime":"2016-06-14 11:00:00.0","useTime":"2016-06-14 08:46:02.0"},{"orderId":2761888,"shopId":2086,"shopCode":"54037","shopName":"黄石体育馆-羽毛球馆","sales":"张文","cityId":14,"cityName":"黄石","sportsType":4,"sportsTypeName":"羽毛球","orderNumber":1,"paySum":0,"fee":0,"subsidySum":0,"subsidyFee":0,"payType":null,"status":3,"statusName":"已使用","settleStatus":1,"settleStatusName":"未结算","orderTime":"2016-06-13 11:08:57.0","examineTime":"2016-06-14 16:00:00.0","useTime":"2016-06-14 13:55:16.0"},{"orderId":2762522,"shopId":2086,"shopCode":"54037","shopName":"黄石体育馆-羽毛球馆","sales":"张文","cityId":14,"cityName":"黄石","sportsType":4,"sportsTypeName":"羽毛球","orderNumber":1,"paySum":0,"fee":0,"subsidySum":0,"subsidyFee":0,"payType":null,"status":3,"statusName":"已使用","settleStatus":1,"settleStatusName":"未结算","orderTime":"2016-06-13 13:23:09.0","examineTime":"2016-06-14 11:00:00.0","useTime":"2016-06-14 08:51:43.0"},{"orderId":2761350,"shopId":2086,"shopCode":"54037","shopName":"黄石体育馆-羽毛球馆","sales":"张文","cityId":14,"cityName":"黄石","sportsType":4,"sportsTypeName":"羽毛球","orderNumber":1,"paySum":0,"fee":0,"subsidySum":0,"subsidyFee":0,"payType":null,"status":3,"statusName":"已使用","settleStatus":1,"settleStatusName":"未结算","orderTime":"2016-06-13 08:05:53.0","examineTime":"2016-06-14 16:00:00.0","useTime":"2016-06-14 13:53:37.0"},{"orderId":2766047,"shopId":2086,"shopCode":"54037","shopName":"黄石体育馆-羽毛球馆","sales":"张文","cityId":14,"cityName":"黄石","sportsType":4,"sportsTypeName":"羽毛球","orderNumber":1,"paySum":0,"fee":0,"subsidySum":0,"subsidyFee":0,"payType":null,"status":3,"statusName":"已使用","settleStatus":1,"settleStatusName":"未结算","orderTime":"2016-06-14 08:58:24.0","examineTime":"2016-06-14 11:00:00.0","useTime":"2016-06-14 08:45:32.0"},{"orderId":2761900,"shopId":2086,"shopCode":"54037","shopName":"黄石体育馆-羽毛球馆","sales":"张文","cityId":14,"cityName":"黄石","sportsType":4,"sportsTypeName":"羽毛球","orderNumber":1,"paySum":0,"fee":0,"subsidySum":0,"subsidyFee":0,"payType":null,"status":3,"statusName":"已使用","settleStatus":1,"settleStatusName":"未结算","orderTime":"2016-06-13 11:12:15.0","examineTime":"2016-06-14 16:00:00.0","useTime":"2016-06-14 13:55:51.0"},{"orderId":2765458,"shopId":2086,"shopCode":"54037","shopName":"黄石体育馆-羽毛球馆","sales":"张文","cityId":14,"cityName":"黄石","sportsType":4,"sportsTypeName":"羽毛球","orderNumber":1,"paySum":0,"fee":0,"subsidySum":0,"subsidyFee":0,"payType":null,"status":3,"statusName":"已使用","settleStatus":1,"settleStatusName":"未结算","orderTime":"2016-06-14 08:13:59.0","examineTime":"2016-06-14 11:00:00.0","useTime":"2016-06-14 08:51:53.0"},{"orderId":2761363,"shopId":2086,"shopCode":"54037","shopName":"黄石体育馆-羽毛球馆","sales":"张文","cityId":14,"cityName":"黄石","sportsType":4,"sportsTypeName":"羽毛球","orderNumber":1,"paySum":0,"fee":0,"subsidySum":0,"subsidyFee":0,"payType":null,"status":3,"statusName":"已使用","settleStatus":1,"settleStatusName":"未结算","orderTime":"2016-06-13 08:07:33.0","examineTime":"2016-06-14 16:00:00.0","useTime":"2016-06-14 13:56:46.0"},{"orderId":2761270,"shopId":2086,"shopCode":"54037","shopName":"黄石体育馆-羽毛球馆","sales":"张文","cityId":14,"cityName":"黄石","sportsType":4,"sportsTypeName":"羽毛球","orderNumber":1,"paySum":0,"fee":0,"subsidySum":0,"subsidyFee":0,"payType":null,"status":3,"statusName":"已使用","settleStatus":1,"settleStatusName":"未结算","orderTime":"2016-06-13 08:02:04.0","examineTime":"2016-06-14 16:00:00.0","useTime":"2016-06-14 13:52:30.0"},{"orderId":2762404,"shopId":2086,"shopCode":"54037","shopName":"黄石体育馆-羽毛球馆","sales":"张文","cityId":14,"cityName":"黄石","sportsType":4,"sportsTypeName":"羽毛球","orderNumber":1,"paySum":0,"fee":0,"subsidySum":0,"subsidyFee":0,"payType":null,"status":3,"statusName":"已使用","settleStatus":1,"settleStatusName":"未结算","orderTime":"2016-06-13 13:03:31.0","examineTime":"2016-06-14 16:00:00.0","useTime":"2016-06-14 13:56:20.0"},{"orderId":2761375,"shopId":2086,"shopCode":"54037","shopName":"黄石体育馆-羽毛球馆","sales":"张文","cityId":14,"cityName":"黄石","sportsType":4,"sportsTypeName":"羽毛球","orderNumber":1,"paySum":0,"fee":0,"subsidySum":0,"subsidyFee":0,"payType":null,"status":4,"statusName":"已过期(未使用)","settleStatus":1,"settleStatusName":"未结算","orderTime":"2016-06-13 08:10:06.0","examineTime":"2016-06-14 11:00:00.0","useTime":null},{"orderId":2765501,"shopId":2086,"shopCode":"54037","shopName":"黄石体育馆-羽毛球馆","sales":"张文","cityId":14,"cityName":"黄石","sportsType":4,"sportsTypeName":"羽毛球","orderNumber":1,"paySum":0,"fee":0,"subsidySum":0,"subsidyFee":0,"payType":null,"status":3,"statusName":"已使用","settleStatus":1,"settleStatusName":"未结算","orderTime":"2016-06-14 08:23:05.0","examineTime":"2016-06-14 11:00:00.0","useTime":"2016-06-14 08:51:07.0"},{"orderId":2761366,"shopId":2086,"shopCode":"54037","shopName":"黄石体育馆-羽毛球馆","sales":"张文","cityId":14,"cityName":"黄石","sportsType":4,"sportsTypeName":"羽毛球","orderNumber":1,"paySum":0,"fee":0,"subsidySum":0,"subsidyFee":0,"payType":null,"status":3,"statusName":"已使用","settleStatus":1,"settleStatusName":"未结算","orderTime":"2016-06-13 08:08:00.0","examineTime":"2016-06-14 16:00:00.0","useTime":"2016-06-14 13:57:31.0"},{"orderId":2761326,"shopId":2086,"shopCode":"54037","shopName":"黄石体育馆-羽毛球馆","sales":"张文","cityId":14,"cityName":"黄石","sportsType":4,"sportsTypeName":"羽毛球","orderNumber":1,"paySum":0,"fee":0,"subsidySum":0,"subsidyFee":0,"payType":null,"status":3,"statusName":"已使用","settleStatus":1,"settleStatusName":"未结算","orderTime":"2016-06-13 08:04:28.0","examineTime":"2016-06-14 16:00:00.0","useTime":"2016-06-14 13:53:15.0"},{"orderId":2768259,"shopId":2086,"shopCode":"54037","shopName":"黄石体育馆-羽毛球馆","sales":"张文","cityId":14,"cityName":"黄石","sportsType":4,"sportsTypeName":"羽毛球","orderNumber":1,"paySum":0,"fee":0,"subsidySum":0,"subsidyFee":0,"payType":null,"status":3,"statusName":"已使用","settleStatus":1,"settleStatusName":"未结算","orderTime":"2016-06-14 14:18:22.0","examineTime":"2016-06-14 16:00:00.0","useTime":"2016-06-14 14:34:37.0"},{"orderId":2761678,"shopId":2086,"shopCode":"54037","shopName":"黄石体育馆-羽毛球馆","sales":"张文","cityId":14,"cityName":"黄石","sportsType":4,"sportsTypeName":"羽毛球","orderNumber":1,"paySum":0,"fee":0,"subsidySum":0,"subsidyFee":0,"payType":null,"status":4,"statusName":"已过期(未使用)","settleStatus":1,"settleStatusName":"未结算","orderTime":"2016-06-13 09:48:06.0","examineTime":"2016-06-14 11:00:00.0","useTime":null},{"orderId":2766035,"shopId":2086,"shopCode":"54037","shopName":"黄石体育馆-羽毛球馆","sales":"张文","cityId":14,"cityName":"黄石","sportsType":4,"sportsTypeName":"羽毛球","orderNumber":1,"paySum":0,"fee":0,"subsidySum":0,"subsidyFee":0,"payType":null,"status":3,"statusName":"已使用","settleStatus":1,"settleStatusName":"未结算","orderTime":"2016-06-14 08:57:25.0","examineTime":"2016-06-14 11:00:00.0","useTime":"2016-06-14 08:46:19.0"},{"orderId":2761682,"shopId":2086,"shopCode":"54037","shopName":"黄石体育馆-羽毛球馆","sales":"张文","cityId":14,"cityName":"黄石","sportsType":4,"sportsTypeName":"羽毛球","orderNumber":1,"paySum":0,"fee":0,"subsidySum":0,"subsidyFee":0,"payType":null,"status":4,"statusName":"已过期(未使用)","settleStatus":1,"settleStatusName":"未结算","orderTime":"2016-06-13 09:49:19.0","examineTime":"2016-06-14 16:00:00.0","useTime":null}],"firstPage":1,"prePage":0,"nextPage":2,"lastPage":2,"isFirstPage":true,"isLastPage":false,"hasPreviousPage":false,"hasNextPage":true,"navigatePages":8,"navigatepageNums":[1,2]};          //订单明细
        $scope.detailDisplay=false;    //是否显示订单明细
        $scope.currentDetailParams={}; //当前订单详情的查询参数
        $scope.loading=false;           //是否正在加载
        $scope.exports={statistics:[
            {action:"export/excel/GeneralExcel",name:"导出财务综合表"}
        ],orders:[
            {action:"export/excel/dataCountDetails",name:"导出订单明细"}
        ]};
        $scope.dimensionOpt={
            opt:"<<<<>>>>",
            select:function(index,opt){
                if(opt=='in'){
                    $scope.selector.currentDimensions.push($scope.selector.dimensions.splice(index,1)[0]);
                }
                else{
                    $scope.selector.dimensions.push($scope.selector.currentDimensions.splice(index,1)[0]);
                }
                if($scope.selector.currentDimensions.length==0){
                    this.opt="<<<<<<<<";
                }
                else if($scope.selector.dimensions.length==0){
                    this.opt="";
                }
                else{
                    this.opt="<<<<>>>>";
                }
                $scope.results=[];
                resetTitle();
            },
            over:function(opt){
                if(opt=='out'){
                    this.opt=">>>>>>>>";
                }
                else{
                    this.opt="<<<<<<<<";
                }
            },
            leave:function(){
                if($scope.selector.currentDimensions.length==0){
                    this.opt="<<<<<<<<";
                }
                else if($scope.selector.dimensions.length==0){
                    this.opt="";
                }
                else{
                    this.opt="<<<<>>>>";
                }
            }
        };

        function addDate(dadd,dd){
            var a = dd?new Date(dd):new Date();
            a = a.valueOf();
            a = a + dadd * 24 * 60 * 60 * 1000;
            a = new Date(a);
            var year=a.getFullYear();
            var month=a.getMonth()<9?'0'+(a.getMonth()+1):a.getMonth()+1;
            var date= a.getDate()<10?'0'+ a.getDate(): a.getDate();
            return year+"-"+ month+"-"+ date;
        }
        /**
         * 切换到订单详情
         * @param settle    结果集对象
         */
        $scope.showDetail=function(settle){
            $scope.detailDisplay=true;
            $scope.orderDetail={};
            var detailParam={};
            for(var key in $scope.searchInfo) {
                detailParam[key]=$scope.searchInfo[key];
            }
            for(key in settle.dimensionParam) {
                detailParam[key]=settle.dimensionParam[key];
            }
            $scope.currentDetailParams=detailParam;
            console.log($scope.currentDetailParams);
            $http.get("api/order/load/dataCountDetails",{params:$scope.currentDetailParams}).success(function(data){
                $scope.orderDetail=data;
                console.log(data);
            });
        };
        /**
         * 订单详情翻页
         * @param pageNum   页数
         */
        $scope.loadDetailByPage=function(pageNum){
            $scope.currentDetailParams.pageNum=pageNum;
            if(pageNum>0 && pageNum!=$scope.orderDetail.pageNum && pageNum<=$scope.orderDetail.pages){
                $http.get("api/order/load/dataCountDetails",{params:$scope.currentDetailParams}).success(function(data){
                    console.log(data);
                    $scope.orderDetail=data;
                });
            }
        };
        $scope.closeDetail=function(){
            $scope.detailDisplay=false;
        };
        /**
         * 初始化下拉框
         */
        var initSelector=function(){
            $http.get("api/order/selectList").success(function(data){
                //console.log(data);
                $scope.selector={
                    collapse:true,
                    toggleCollapse:function(){
                        this.collapse=!this.collapse;
                    },
                    timeType:data.selectTimeType,
                    groups:[
                        {key:"-1",value:"全国",active:true},
                        {key:"1",value:"湖北"},
                        {key:"2",value:"湖南"}
                    ],
                    payType:data.selectPayType,
                    orderType:data.selectOrderType,
                    orderStatus:data.selectOrderStatus,
                    city:data.selectCityType,
                    sportsType:data.selectSportsType,
                    currentDimensions:[],
                    dimensions:data.selectDimension,
                    click:function(index,property){
                        for(var i=0;i<this[property].length;i++){
                            this[property][i].active=(i==index);
                        }
                        var key=this[property][index].key;
                        if(key&&key.length>0){
                            $scope.searchInfo[property]=key;
                        }
                        else{
                            delete $scope.searchInfo[property];
                        }
                    }
                };
                $scope.currentTimeType=$scope.selector.timeType[0];
                $scope.selector.city.unshift({key:'',value:'所有',active:true});
                $scope.selector.payType.unshift({key:'',value:'所有',active:true});
                $scope.selector.orderType.unshift({key:'',value:'所有',active:true});
                $scope.selector.orderStatus[0].active=true;
                $scope.searchInfo.orderStatus=$scope.selector.orderStatus[0].key;
                $scope.selector.sportsType.unshift({key:'',value:'所有',active:true});
                $scope.selector.currentDimensions.push($scope.selector.dimensions.splice(0,1)[0]);

                resetTitle();
            });
        };

        /**
         * 搜索原始统计数据
         */
        $scope.loadResult=function(){
            //$scope.searchInfo={};
            //日期类型
            if($scope.currentTimeType&&$scope.currentTimeType.key){
                $scope.searchInfo.timeType=$scope.currentTimeType.key;
            }
            //日期起始
            if($scope.startTime>$scope.endTime){
                alert("开始时间必须小于结束时间");
                return;
            }
            /*
             else if(addDate(62,$scope.startTime)<$scope.endTime){
                alert("时间跨度最大为两个月");
                return;
            }*/
            else{
                $scope.searchInfo.startTime=$scope.startTime;
                $scope.searchInfo.endTime=$scope.endTime;
            }
            //维度
            if($scope.selector.currentDimensions.length==0){
                alert("请至少选择一个统计维度");
                return;
            }
            else{
                var dimensionStr="";
                for(var i=0;i<$scope.selector.currentDimensions.length;i++){
                    var d=$scope.selector.currentDimensions[i];
                    if(dimensionStr==""){
                        dimensionStr+= d.key;
                    }
                    else{
                        dimensionStr+= ","+d.key;
                    }
                }
                $scope.searchInfo.dimensions=dimensionStr;
            }
            $scope.results=[];
            //收起搜索栏
            $('#searchBody').collapse('hide');
            //关闭详情
            $scope.detailDisplay=false;
            //$("#searchBody").removeClass('collapse').addClass('collapsing');
            $http.get("api/order/count/orderData",{params:$scope.searchInfo}).success(function(data){
                buildResult(data);
            });
        };
        /**
         * 自定义导出
         */
        $scope.customExport=function(ex){
            var action=ex.action;
            $("#exportForm").attr("action",action).submit();
        };
        /**
         * 导出
         */
        $scope.exportResult=function(){
            $scope.resultsStr="";
            for(var i=0;i<$scope.selector.currentDimensions.length;i++){
                var title=$scope.selector.currentDimensions[i].value;
                if(i==$scope.shopDimensionIndex){
                    title="场馆Id,场馆名称"
                }
                if(i==0){
                    $scope.resultsStr+=title;
                }
                else{
                    $scope.resultsStr+=","+title;
                }
            }
            $scope.resultsStr+=",订单数,场次数,交易额,交易服务费,补贴额,补贴服务费,总金额,总服务费,结算额\n";
            for(i=0;i<$scope.results.length;i++){
                var cols=$scope.results[i].cols;
                for(var j=0;j<cols.length;j++){
                    if(j==0){
                        $scope.resultsStr+=cols[j];
                    }
                    else{
                        $scope.resultsStr+=","+cols[j];
                    }
                }
                $scope.resultsStr+="\n";
            }

            var BB = self.Blob;
            saveAs(
                new BB(
                    ["\ufeff" + $scope.resultsStr] //\ufeff防止utf8 bom防止中文乱码
                    , {type: "text/plain;charset=utf8"}
                )
                , 'results.csv'
            );
        };
        /**
         * 重置结果集标题
         */
        var resetTitle=function(){
            $scope.titles=[];
            $scope.shopDimensionIndex=-1;
            for(var i=0;i<$scope.selector.currentDimensions.length;i++){
                var dimension=$scope.selector.currentDimensions[i];
                if(dimension.key == 'shop'){
                    $scope.shopDimensionIndex=i;
                    $scope.titles.push("场馆Id");
                    $scope.titles.push("场馆名称");
                }
                else{
                    $scope.titles.push(dimension.value);
                }
            }
            $scope.titles.push("订单数");
            $scope.titles.push("场次数");
            $scope.titles.push("交易额");
            $scope.titles.push("交易服务费");
            $scope.titles.push("补贴额");
            $scope.titles.push("补贴服务费");
            $scope.titles.push("总金额");
            $scope.titles.push("总服务费");
            $scope.titles.push("结算额");
        };
        /**
         * 创建2维结果集
         * @param results   结果集对象
         * @param index     维度层数
         * @param dp        维度本身的元数据
         */
        var buildResult=function(results,index,dp){
            var dimensionParam={};
            var subResults=results.subSettlements;
            if(dp){
                for(var key in dp){
                    dimensionParam[key]=dp[key];
                }
            }
            else{
                dimensionParam={};
            }
            if(!index)index=0;
            var cols=[];
            var cIndex=index;
            var dCount=$scope.selector.currentDimensions.length;
            var sIndex=$scope.shopDimensionIndex;
            var printBlank=function(count){
                for(var i=0;i<count;i++){
                    cols.push("")
                }
            };
            //cols.push(cIndex+"-"+sIndex+"-"+dCount);
            if(sIndex<0){
                printBlank(cIndex-1);
                cols.push(results.title);
                if(cIndex<dCount&&cIndex>0){
                    cols.push("总");
                }
                printBlank(dCount-cIndex-1);
                //cols.push(1);
            }
            else{
                if(cIndex-1==sIndex){
                    printBlank(cIndex-1);
                    cols.push(results.value);
                    cols.push(results.title);
                    if(cIndex<dCount&&cIndex>0){
                        cols.push("总");
                    }
                    printBlank(dCount-cIndex-1);
                    //cols.push(2);
                }
                else if(cIndex-1<sIndex){
                    printBlank(cIndex-1);
                    cols.push(results.title);
                    if(cIndex<dCount&&cIndex>0){
                        cols.push("总");
                    }
                    printBlank(dCount-cIndex);
                    //cols.push(3);
                }
                else{
                    printBlank(cIndex);
                    cols.push(results.title);
                    if(cIndex<dCount&&cIndex>0){
                        cols.push("总");
                    }
                    printBlank(dCount-cIndex-1);
                    //cols.push(4);
                }
            }
            cols.push(results.count);
            cols.push(results.orderNum);
            cols.push(results.paySum.toFixed(2));
            cols.push(results.fee.toFixed(2));
            cols.push(results.subsidySum.toFixed(2));
            cols.push(results.subsidyFee.toFixed(2));
            cols.push(results.totalSum.toFixed(2));
            cols.push(results.feeSum.toFixed(2));
            cols.push(results.settlementSum.toFixed(2));
            var result={layer:index,dimensionParam:dimensionParam,cols:cols,baseList:results.baseList};
            if(index>0){
                result.dimensionParam[$scope.selector.currentDimensions[index-1].key]=results.value;
            }
            $scope.results.push(result);
            for(var i=0;i<subResults.length;i++){
                buildResult(subResults[i],index+1,dimensionParam);
                //if(i>3)break;
            }
        };
        initSelector();
        //loadResults();
    });
});
